﻿using System.IO;
using System.Web.Mvc;
using Blog.Models;
using Business;

namespace Blog.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index(int id = 1)
        {
            ViewBag.Message = "Bienvenue sur le blog du Chant du Canard!";

            AboutModel.TextToShow = this.GetTextAbout();

            return View(ArticlesManager.ReadLast());
        }

        public ActionResult About()
        {
            ViewBag.Message = "A propos...";

            return View();
        }

        private string GetTextAbout()
        {
            string dir = Server.MapPath("/Content");
            string fichier = dir + "\\About.txt";
            string text = "";

            using (StreamReader streamReader = new StreamReader(fichier.ToString()))
            {
                string line;
          
                while ((line = streamReader.ReadLine()) != null)
                {
                    text += line;
                }
            }

            return text;
        }

        [Authorize]
        public ActionResult AboutEdit()
        {
            ViewBag.Message = "Editez le contenu";

            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult AboutEdit(AboutModel about)
        {
            string dir = Server.MapPath("../Content");
            string fichier = dir + "\\About.txt";

            using (StreamWriter streamWriter = new StreamWriter(fichier.ToString()))
            {
                streamWriter.Write(about.Text);
            }

            AboutModel.TextToShow = about.Text;
            
            return RedirectToAction("Index", "Home");
        }
    }
}
